<template>
    <div>
        <el-button type="success" @click="AddRouter">添加角色</el-button>
        <br>
        <br>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="" type="index" label="编号" align="center" />
            <el-table-column prop="roleName" label="角色名称" align="center">
                <template v-slot="scoped">
                    <a href="#" @click="save(scoped.row.roleName, scoped.row.roleId)">{{ scoped.row.roleName }}</a>
                </template>
            </el-table-column>
            <el-table-column prop="createName" label="创建人" align="center" />
            <el-table-column prop="createTime" label="创建日期" align="center">
                <template v-slot="scoped">
                    {{ scoped.row.createTime.substring(0, 10) + " " + scoped.row.createTime.substring(11, 19) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateName" label="修改人" align="center">
                <template v-slot="scoped">
                    <span v-if="!scoped.row.updateName">{{ "--" }}</span>
                    <span v-else>{{ scoped.row.updateName }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="修改日期" align="center">
                <template v-slot="scoped">
                    {{ scoped.row.updateTime ? scoped.row.updateTime.substring(0, 10) + " "+scoped.row.updateTime.substring(11,19):null }}
                </template>
            </el-table-column>
            <el-table-column prop="date" label="操作" width="160" align="center">
                <template v-slot="scoped">
                    <el-link style="margin: 0 3px;" type="warning" size="small"
                        @click="UpDateRouter(scoped.row.roleId)">修改</el-link>
                    <el-link style="margin: 0 3px;" type="danger" size="small"
                        @click="Del(scoped.row.roleId)">删除</el-link>
                    <el-link style="margin: 0 3px;" type="primary" size="small"
                        @click="FenPei(scoped.row.roleId, scoped.row.roleName)">分配人员</el-link>
                        <el-link style="margin: 0 3px;" type="primary" size="small"
                        @click="FenPeiq(scoped.row.roleId, scoped.row.roleName)">分配权限</el-link>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!--角色修改 对话框 -->
    <div>
        <el-dialog v-model="dialogFormVisibleUpdate" title="修改角色" width="500">
            <el-form :model="form">
                <el-form-item label="角色名称" prop="roleName" @change="OneUserName">
                    <el-input v-model="form.roleName" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisibleUpdate = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">
                        修改
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
    <!--角色分配 对话框 -->
    <div>
        <el-dialog v-model="dialogFormVisibleFenPei" width="500">
            <h3 style="margin-bottom: 33px;">请设置<span style="color: red;">【{{ roleNamefen }}】</span>角色的员工</h3>
            <!-- 左右布局 -->
            <div class="common-layout">
                <el-container>
                    <el-aside style="height: 300px; width: 200px;">
                        <!-- 部门加载 -->
                        <div>
                            <div>
                                <el-tree :data="DepData" show-checkbox node-key="value" ref="treeRef"
                                    :props="defaultProps" :default-checked-keys="defaultCheckedKeys"
                                    @check-change="handleCheckChange" default-expand-all="true"></el-tree>
                            </div>
                        </div>
                    </el-aside>
                    <el-aside style="height: 300px; width: 200px;">
                        <!-- 用户根据部门加载 -->
                        <div>
                            <p style="margin-bottom: 15px;">选择员工</p>
                            <el-checkbox-group v-model="userrolevules.userIds">
                                <el-checkbox style="display: block;" v-for="items in uservule" :key="items.userId"
                                    :label="items.name" :value="items.userId" />
                            </el-checkbox-group>
                        </div>
                    </el-aside>
                </el-container>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisibleFenPei = false">取消</el-button>
                    <el-button type="primary" @click="RoleUserAdd">
                        确定保存
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <!-- 角色查看用户弹出框 -->
    <div>
        <el-dialog v-model="dialogFormVisible2" title="" width="500">
            <h3>属于角色<span style="color: red;">【{{ roleVlues.roleName }}】</span>的员工如下</h3>
            <el-button type="success" size="small" style="margin-top: 5px;"
                @click="pprole(roleVlues.roleName, roleVlues.roleId)">添加用户</el-button>
            <el-table :data="getUserNamelist" border style="margin-top: 10px;width: 100%">
                <el-table-column prop="userName" label="员工名称" />
                <el-table-column label="操作">
                    <template v-slot="scoped">
                        <el-button type="danger" size="small" @click="Delur(scoped.row.userRoleId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible2 = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import {axios} from '@/axios/axiosHelp'
import { ElMessage, ElMessageBox } from 'element-plus';

import { compile, computed, onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import DepData from '@/stores/departmentData'


//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();

//添加条转
const AddRouter = () => {
    router.push("/AddRole")
}




//#region 对话框角色显示================================================================================
//角色对话框开关
const dialogFormVisible2 = ref(false)

const pproleName = ref("")

//存放用户昵称
const getUserNamelist = ref([])
//分配人员弹出框
const pprole = (roleName: any, roleId: any) => {
    //打开分配角色对话框
    dialogFormVisibleFenPei.value = true
    FenPei(roleId, roleName);
    pproleName.value = roleName;
}

//角色查询id存放
const roleVlues = reactive({
    roleId: 0,
    roleName: "",
})


//1.打开角色显示对话框 2.传值(角色id)查询用户对应名称
const save = (roleName: any, roleId: number) => {
    //角色对话看显示--打开
    dialogFormVisible2.value = true
    roleVlues.roleId = roleId
    roleVlues.roleName = roleName;
    getroleuserList();
}

//通过角色id查询用户名称
const getroleuserList = () => {
    axios.get(`http://localhost:7081/api/User/GetUserNameRoleId?RoleId=` + roleVlues.roleId).then(res => {
        getUserNamelist.value = res.data.data
    })
}


//删除用户角色
const Delur = (ids: any) => {
    ElMessageBox.confirm(
        '你确定删除吗?',
        '提示',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("https://localhost:7181/api/User/RemoveUserRole", {
                "userRoleId": [
                    ids
                ]
            }).then(res => {
                if (res.data.code == 100) {
                    ElMessage.success(res.data.msg);
                    getroleuserList();
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

//#endregion


//#region对话框角色分配 ================================================================================
//角色分配对话框开关
const dialogFormVisibleFenPei = ref(false)

//树形结构
const defaultProps = {
    children: 'children',
    label: 'label',
}

//部门信息存储
const Depvalue = ref([])

//获取用户信息
const uservule = ref()
//选择保存用户ID
const UserIdvalue = ref()
//树形节点保存
const treeRef = ref()
//部门id查询用户id
const handleCheckChange = () => {
    Depvalue.value = treeRef.value.getCheckedKeys();
    const aa = Depvalue.value.join(",")
    console.log(aa, '选择的部门id')
    axios.get("http://localhost:7081/api/User/GetUserName", {
        params: {
            DepId: aa
        }
    }).then(res => {
        uservule.value = res.data.data
    })
}

//显示角色名称
const roleNamefen = ref('')

//分配人员
const FenPei = (roleids: any, roleName: any) => {
    dialogFormVisibleFenPei.value = true
    //角色ID 赋值
    userrolevules.value.roleId = roleids
    //显示角色名称赋值
    roleNamefen.value = roleName
    // 清空 defaultCheckedKeys 的方法
    clearCheckedKeys();
    //反填用户名称
    FanTianUserName(roleids);
}

// 设置默认勾选的部门节点的 key 值
const defaultCheckedKeys = ref([]);

//反填用户名称
const FanTianUserName = (roleids: Number) => {
    defaultCheckedKeys.value = []
    Depvalue.value = []
    axios.get(`http://localhost:7081/api/User/GetUserNameRoleId?RoleId=` + roleids).then(res => {
        const data = res.data.data
        //反填用户
        const userids = data.map((x: any) => x.userId)
        // 设置默认选中的用户ID
        userrolevules.value.userIds = userids
        console.log(userids, '反填用户ids')
        //反填部门
        const depids = data.map((x: any) => x.depId);
        const depIdVule = [...new Set(depids)];
        defaultCheckedKeys.value = depIdVule
    })
}

// 清空 defaultCheckedKeys 的方法
const clearCheckedKeys = () => {
    defaultCheckedKeys.value = [];
    if (treeRef.value) {
        treeRef.value.setCheckedKeys([]);
    }
};

//添加用户角色数据
const userrolevules = ref({
    "roleId": 0,
    "userIds": []
})

//批量添加
const RoleUserAdd = () => {
    pprole;
    console.log(userrolevules.value.roleId, "批量删除的角色id")
    console.log(userrolevules.value.userIds, "批量添加的用户id")
    //第一步删除 通过 角色ID批量删除
    axios.post("https://localhost:7181/api/User/UserRoleRemoveRange", userrolevules.value).then(res => {
        if (res.data.code == 100) {
            // ElMessage.success(res.data.msg)
        }
    })
    //第二步批量添加
    axios.post('https://localhost:7181/api/User/UserRoleAddRanges', userrolevules.value).then(res => {
        if (res.data.code == 100) {
            ElMessage.success("人员更新成功")
        } else {
            // ElMessage.success(res.data.msg)
        }
        getroleuserList();
    })


    //关闭分配对话框
    dialogFormVisibleFenPei.value = false
}

//角色对话框对话框开关
const Off = () => {
    //关闭角色对话框
    dialogFormVisible2.value = false
    //打开角色对话框
    dialogFormVisible2.value = false
}


//#endregion

//#region 修改对话框

//对话框 开关
const dialogFormVisibleUpdate = ref(false)

//参数
const form = reactive({
    "roleId": 0,
  "roleName": "",
  "createUser": "",

  "updateUser": "",


})


//修改反填
const UpDateRouter = (ids: any) => {
    dialogFormVisibleUpdate.value = true
    axios.get(`http://localhost:7081/api/User/RoleFanTian?RoleId=` + ids).then(res => {
        form.roleId = res.data.data.roleId
        form.roleName = res.data.data.roleName

    })
}

//姓名唯一验证状态
const Status = reactive({
    OneNameStatu: 1, //1通过名不称重复 2不通过名称重复
})
//姓名唯一验证
const OneUserName = () => {
    axios.get(`http://localhost:7081/User/OneRoleName?RoleName=` + form.roleName).then(res => {
        if (res.data.code == 101) {
            ElMessage.error(res.data.msg)
            return Status.OneNameStatu = 2;
        } else {
            ElMessage.success(res.data.msg)
            return Status.OneNameStatu = 1;
        }
    })
}

//修改事件
const submitForm = () => {
    if (form.roleName == "") {
        ElMessage.error("角色名称不可为空")
        return
    }
    if (Status.OneNameStatu == 2) {
        ElMessage.error("用户名称重复")
        return;
    }
    axios.post("https://localhost:7181/api/User/RoleUpdate", form).then(res => {
        if (res.data.code == 100) {
            ElMessage.success(res.data.msg)
            dialogFormVisibleUpdate.value = false
            show()
        } else {
            ElMessage.success("修改出错")
        }
    })
}


//#endregion





//#region 角色页面显示
//显示
const tableData = ref([])
const show = () => {
    axios.get('http://localhost:7081/api/User/GetRole').then(res => {
        tableData.value = res.data.data
    })
}

//#endregion


//#region 角色删除
//角色删除
const Del = (ids: any) => {
    ElMessageBox.confirm(
        '你确定删除吗?',
        '提示',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("https://localhost:7181/api/User/DelRole", {
                "roleId": ids
            }).then(res => {
                if (res.data.code == 100) {
                    ElMessage.success(res.data.msg);
                } else {
                    ElMessage.error(res.data.msg);
                }
                show();
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

//#endregion


onMounted(() => {
    show();
})

</script>

<style scoped></style>